package com.awa.usercenter.filter;

import com.awa.usercenter.common.utils.JwtUtils;
import com.awa.usercenter.model.domain.User;
import com.awa.usercenter.model.domain.UserRole;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * 捕获请求头，获取用户信息
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Authorization");
        // 没有token直接放行
        if(token == null){
            doFilter(request,response,filterChain);
            return;
        }
        // 有token
        Claims claims = jwtUtils.parseToken(token);
        // 获取数据
        Long userId = claims.get("userId", Long.class);
        String phone = claims.get("phone", String.class);
        ArrayList<LinkedHashMap> userRoles = new ArrayList<>();
        Set<UserRole> roles = new HashSet<>();
        userRoles = claims.get("roles", ArrayList.class);
        for (LinkedHashMap Role : userRoles) {
            UserRole singleUserRole = new UserRole()
                    .setRoleId((int) Role.get("roleId"))
                    .setRoleName((String) Role.get("roleName"));
            roles.add(singleUserRole);
        }
        User user = new User().setUserId(userId).setPhone(phone).setRoleSet(roles);
        //todo
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        doFilter(request,response,filterChain);
    }
}
